// egret是支持多重纹理的，详细见：
// http://bbs.egret.com/thread-51121-1-3.html

// 不能异步的实现，必须上来就读取！

enum ShaderNameEnum {
	vertex = 'default_vert',
	mapblock = 'mapBlock',
	mapMask = 'mapMask',
	gaosiBlur = 'gaosiBlur',
	fragBlur = 'frogBlur',
	frogLight = 'frogLight',
	bShadow = 'bShadow',
}

async function loadShaderFile(file: string): Promise<string> {
	const fullfile = `resource/shader/${file}.glsl`;
	if (isEditor()) {
		const buf = FsUtils.readFileSync(fullfile);
		return buf.toString();
	}
	return RES.getResByUrl(fullfile, null, null, RES.ResourceItem.TYPE_TEXT);
}

function loadShader(file: string): string {
	const glslfile = `${file}_glsl`;
	return RES.getRes(glslfile);
}

const shaders: Record<string, string> = {};
function loadShaders() {
	for (const shader of Object.values(ShaderNameEnum)) {
		shaders[shader] = loadShader(shader);
	}
}

function getShader(file: string): string {
	return shaders[file];
}

let vertexSrc = '';

function getVertexSrc(): string {
	if (!vertexSrc) {
		vertexSrc = getShader(ShaderNameEnum.vertex);
	}
	return vertexSrc;
}

async function asyncGetFillter(fragFile: string, uniforms?: any): Promise<egret.CustomFilter> {
	const data = await loadShaderFile(fragFile);
	if (data) {
		const fillter = new egret.CustomFilter(getVertexSrc(), data, uniforms);
		return fillter;
	}
	return null;
}

async function setShader(obj: egret.DisplayObject, file: string) {
	const filtter = await asyncGetFillter(file);
	if (filtter) {
		obj.filters = [filtter];
	}
}

function getFillter(fragFile: string, uniforms?: any): egret.CustomFilter {
	const fillter = new egret.CustomFilter(getVertexSrc(), getShader(fragFile), uniforms);
	egret.assert(fillter != null);
	return fillter;
}

let gMapBlockFillter: egret.CustomFilter;
function getMapBlockFillter(): egret.CustomFilter {
	if (!gMapBlockFillter) {
		gMapBlockFillter = getFillter('mapBlock');
	}
	return gMapBlockFillter;
}

let gMapMaskFillter: egret.CustomFilter;
function getMapMaskFillter(): egret.CustomFilter {
	if (!gMapMaskFillter) {
		gMapMaskFillter = getFillter('mapMask');
	}
	return gMapMaskFillter;
}

function getGaosiBlurFillter(x: number, y: number): egret.CustomFilter {
	return getFillter('gaosiBlur', {
		blur: { x, y },
		uTextureSize: { x: 0, y: 0 },
	});
}

function getFrogBlurFillter(x: number, y: number): egret.CustomFilter {
	return getFillter('frogBlur', {
		blur: { x, y },
		uTextureSize: { x: 0, y: 0 },
	});
}

let gFrogLightFillter: egret.CustomFilter;
function getFrogLightFillter(): egret.CustomFilter {
	if (!gFrogLightFillter) {
		gFrogLightFillter = getFillter('frogLight');
	}
	return gFrogLightFillter;
}

let gBuildingShadowFillter: egret.CustomFilter;
function getBuildingShadowFillter(): egret.CustomFilter {
	if (!gBuildingShadowFillter) {
		gBuildingShadowFillter = getFillter('bShadow');
	}
	return gBuildingShadowFillter;
}
